<template>
	<div class="contents">
		<div class="neworder">
			<!-- <p class="newOrder-title">
				<strong>.</strong>
				基本信息
			</p>
			<div class="new-order-main">
				<el-form :inline="true" :model="formData" class="demo-form-inline">
					<el-form-item label="客户">
						<el-input disabled :value="titleContent.customerName"></el-input>
					</el-form-item>
					<el-form-item label="预计收货时间">
						<el-input disabled :value="titleContent.expectTime"></el-input>
					</el-form-item>
					<el-form-item label="发货时间">
						<el-input disabled :value="titleContent.deliveryTime"></el-input>
					</el-form-item>
				</el-form>
			</div> -->
			<!-- <p class="newOrder-address" style="display: flex;">
				<span style="margin-right: 30px;">标签：</span>
				<span v-for="(item,index) in titleContent.tags" :key="index">{{item}}</span>
			</p> -->
			<h3>收货信息:</h3>
			<div class="newOrder-address">
				<span>收货人：{{ titleContent.customerName }}</span>
				<span>联系电话：{{ titleContent.customerPhone }}</span>
				<span>收货地址：{{ titleContent.customerAddr }}</span>
				<!-- <div>
					预计收货时间：{{ titleContent.expectTime }}
				</div> -->
			</div>
			<div v-show="!handleshow">
				<el-table :data="tableData" border style="width: 100%;">
					<el-table-column type="index" width="50" label="序号"></el-table-column>
					<el-table-column label="商品" prop="a" width="180">
						<template slot-scope="scope">
							<div>{{scope.row.productName}}</div>
						</template>
					</el-table-column>
					<el-table-column label="商品图片">
						<template slot-scope="scope">
							<el-image :src="scope.row.goodsImages.path"></el-image>
						</template>
					</el-table-column>
					<el-table-column label="发货日期" prop="timeDelivery" width="180"/>
					<el-table-column label="商品确认收货图片" width="180" class-name="table_img">
						<template slot-scope="scope">
							<div v-for="(item,index) in scope.row.itemPhotoes" :key="index">
								<el-image :src="item.path" style="width: 50px; height: 50px;"
									:preview-src-list="[item.path] " />
							</div>
						</template>
					</el-table-column>
					<el-table-column prop="goodsInfo.detail" label="描述"></el-table-column>
					<el-table-column prop="unit" label="单位"></el-table-column>
					<el-table-column label="下单数量">
						<template slot-scope="scope">
							<div>
								{{scope.row.qty}}
							</div>
							<!-- <el-input v-model="scope.row.qty" :disabled="scope.row.status != 1"></el-input> -->
						</template>
					</el-table-column>
					<el-table-column prop="shelfPrice" label="市场价(元)" v-if="roles != 'customer'">
						<template slot-scope="scope">
							{{ scope.row.shelfPrice | filterMoney }}
						</template>
					</el-table-column>
					<el-table-column  label="市场价总金额(元)" width="160"  v-if="roles != 'customer'">
						<template slot-scope="scope">
							{{ scope.row.qty * scope.row.shelfPrice | filterMoney }}
						</template>
					</el-table-column>
					<el-table-column label="类型价(元)">
						<template slot-scope="scope">
							{{ scope.row.price | filterMoney }}
						</template>
					</el-table-column>
					<el-table-column label="类型价总金额(元)" width="160">
						<template slot-scope="scope">
							{{ scope.row.qty * scope.row.price | filterMoney }}
						</template>
					</el-table-column>
					<!-- <el-table-column prop="" label="备注">
						<template slot-scope="scope">
							<el-input v-model="scope.row.remarks"></el-input>
						</template>
					</el-table-column> -->
					<!-- <el-table-column prop="address" label="操作" width="250">
						<template slot-scope="scope">
							<el-popconfirm title="是否确定本订单？" @confirm="sure(scope.row,2)">
								<el-button slot="reference" size="mini" type="text"
									v-permissions="['Admin','business','supplier']" v-if="scope.row.status == 1">
									确认订单
								</el-button>
							</el-popconfirm>
							<el-popconfirm title="确定发货订单吗？" @confirm="delivery(scope.row,3)">
								<el-button slot="reference" size="mini" type="text" style="margin-left:10px;"
									v-permissions="['Admin','business','supplier']" v-if="scope.row.status == 2">
									发货
								</el-button>
							</el-popconfirm>
							<el-popconfirm title="确定发货订单吗？" @confirm="delivery(scope.row,4)">
								<el-button slot="reference" size="mini" type="text" style="margin-left:10px;"
									v-permissions="['Admin','purchase','customer']" v-if="scope.row.status == 3">
									确定收货
								</el-button>
							</el-popconfirm>
							<el-popconfirm title="确定确定退货吗？" @confirm="returnGoods(scope.row,5)">
								<el-button slot="reference" size="mini" type="text" style="margin-left:10px;"
									v-permissions="['Admin','purchase','customer']" v-if="scope.row.status == 4">
									退货
								</el-button>
							</el-popconfirm>
							<el-popconfirm title="确定取消本条商品订单吗？" @confirm="sure(scope.row,6)" >
								<el-button slot="reference" size="mini" type="text">
									取消订单
								</el-button>
							</el-popconfirm>
						</template>
					</el-table-column> -->
				</el-table>
				<div class="newOrder-amount">
					<div>
						<span>类型价合计金额：¥</span>
						<span>{{ totalPrice.toFixed(2) }}</span>
					</div>
					<div v-if="roles != 'customer'">
						<span>市场价合计金额：¥</span>
						<span>{{ totalPriceSc.toFixed(2) }}</span>
					</div>
				</div>
				<!-- <div class="newOrder-remark" style="display: flex; align-items: center;">
					<div style="width: 80px;">订单备注</div>
					<el-input placeholder="输入订单备注" maxlength="64" show-word-limit style="width: 100%;"></el-input>
				</div> -->
			</div>

			<div class="newOrder-feature">
				<!-- <el-button :disabled="handleshow" :type="handleshow ? '' : 'primary'">
					核对订单
				</el-button> -->
				<!-- <el-button :disabled="handleshow" :type="handleshow ? '' : 'primary'" @click="handleSave">
					保存并返回列表
				</el-button> -->
				<!-- <el-button :disabled="handleshow" :type="handleshow ? '' : 'primary'">
					保存并继续新增
				</el-button> -->
				<el-button @click="goBackReturn" type="primary" v-if="refer == 1">返回退货列表</el-button>
				<el-button @click="goBack" type="primary" v-else>返回订单列表</el-button>
			</div>
			<el-dialog title="退货" :visible.sync="dialogFormVisible">
				<el-form :model="form">
					<el-form-item label="数量" :label-width="formLabelWidth">
						<el-input v-model="form.qty" type='number' autocomplete="off" placeholder="请输入退货数量"></el-input>
					</el-form-item>
					<el-form-item label="价格" :label-width="formLabelWidth">
						<el-input v-model="form.price" type='number' autocomplete="off" placeholder="请输入退货价格">
						</el-input>
					</el-form-item>
					<el-form-item label="退货类型" :label-width="formLabelWidth">
						<el-select v-model="form.status" placeholder="请选择" style="width: 100%;" disabled>
							<el-option v-for="(item,index) in returnData" :key="index" :label="item.label"
								:value="item.value" />
						</el-select>
					</el-form-item>
					<el-form-item label="退货原因" :label-width="formLabelWidth">
						<el-input type="textarea" v-model="remarks" placeholder="请输入退货原因"></el-input>
					</el-form-item>
					<el-form-item :label-width="formLabelWidth" style="text-align: right;">
						<span>总额：{{form.subtotal}}</span>
					</el-form-item>
				</el-form>
				<div slot="footer" class="dialog-footer">
					<el-button @click="dialogFormVisible = false">取 消</el-button>
					<el-button type="primary" @click="mackOrder">确 定</el-button>
				</div>
			</el-dialog>
		</div>
	</div>
</template>

<script>
	import {
		getOrderAdd,
		getlistitems,
		listitemsedit,
		listitemseditTwo,
		listDetail,
		getDelivery,
		returnGoods,
		addreturn
	} from '@/api/order'
	import { getList } from '@/api/customer/customerProfile'
	import { getGoodsQuery } from '@/api/goodslist'
	import { handleActivePath } from '@/utils/routes'
	import { mapActions } from 'vuex'
	export default {
		inject: ['reload'],
		data() {
			return {
				roles:'',
				returnData: [{
					value: 0,
					label: '退货退款'
				}, {
					value: 1,
					label: '退货'
				}, {
					value: 2,
					label: '仅退款'
				}, ],
				customerId: '',
				formData: {
					wsId: 1,
					customerName: '',
					customerId: '',
					delivery_date: '',
					delievery_time: '',
					type: 'B',
					origin: '后台创建',
					salesId: 1,
					total: 300,
					cuser: this.$store.state.user.username,
				},
				dialogFormVisible: false,
				form: {
					orderId: '',
					productName: '',
					productId: '',
					qty: '',
					unit: '',
					price: '',
					subtotal: '',
					status: 0,
					remarks: '',
					ctime: '',
					customerId: ''
				},
				remarks: '',
				formLabelWidth: '120px',
				dataFilter: {
					pagesize: 10,
					current: 1,
				},
				selectData: [],
				tableData: [],
				userData: {
					customerAddress: {},
				},
				handleshow: false,
				titleContent: "",
				dialogGoods: false,
				refer:'',
				goodsData: [], //商品所有信息
			}
		},
		filters: {
			filterMoney(num) {
				return (num / 100).toFixed(2)
			}
		},
		created() {
			this.id = this.$route.query.id
			this.roles = this.$store.state.user.roles
			this.refer = this.$route.query.refer
			this.getListData()
		},
		computed: {
			totalPrice() {
				let finalPrice = 0
				if (this.tableData.length != 0) {
					for (let book of this.tableData) {
						finalPrice += book.qty * book.price
					}
				}
				return finalPrice.toFixed(2)/100
			},
			totalPriceSc() {
				let sc = 0
				if (this.tableData.length != 0) {
					for (let book of this.tableData) {
						sc += book.qty * book.shelfPrice
					}
				}
				return sc.toFixed(2)/100
			},
			number() {
				const { qty, price } = this.form;
				return {
					qty,
					price
				}
			}
		},
		watch: {
			number(val, e) {
				this.form.subtotal = val.qty * val.price
			}
		},
		methods: {
			async sure(e, index) {
				let res = await listitemsedit({
					id: e.id,
					status: index
				})
				if (res.status == '200') {
					this.$message.success('操作成功')
					this.modifyList(2)
				} else {
					this.$message(res.message)
				}
			},
			async modifyList(e) {
				let res = await listitemseditTwo({
					id: this.id,
					status: e
				})
				if (res.status == '200') {
					this.reload();
					this.getListData()
				} else {
					this.$message(res.message)
				}
			},
			async handleDel(item) {
				let data = {
					id: item.id,
					qty: item.qty,
					price: parseInt(item.price * 100),
					subtotal: parseInt(item.qty * item.price * 100),
				}
				let res = await listitemsedit(data)
				if (res.status == 200) {
					this.$message.success("修改成功")
				} else {
					this.$message.error("修改失败")
				}
			},
			...mapActions({
				delVisitedRoute: 'tabs/delVisitedRoute',
			}),
			async getListData() {
				// alert(this.$store.state.user.roles)
				// let titleres = await listDetail({ id: this.id })
				// this.titleContent = titleres.data
				// this.customerId = titleres.data.customerId
				// this.titleContent.tags = this.titleContent.tags ? this.titleContent.tags.split(',') : ''
				// this.tableData = titleres.data.order
				
				const res = await getlistitems({
					id:this.$route.query.id,
					size:15,
					current:1,
					seq:1
				})
				let titleres = await listDetail({ id: this.id })
				// this.titleContent = titleres.data
				// this.customerId = titleres.data.customerId
				// this.titleContent.tags = this.titleContent.tags ? this.titleContent.tags.split(',') : ''
				this.goodsData = res.data
				res.list.forEach((item) => {
					item.price = item.price / 100
				})
				this.tableData = titleres.data.order
				// console.log(this.tableData,'11111111')
				// this.titleContent = JSON.parse(sessionStorage.getItem('orderList'))
				this.titleContent = titleres.data
			},
			async querySearchAsync(queryString, cb) {
				setTimeout(async () => {
					const ret = await getList(1, 20, {})
					let callBackArr = []
					const res = ret.data.list
					res.forEach((item) => {
						if (item.name.indexOf(queryString) > -1) {
							callBackArr.push(item)
						}
					})
					var newarr = callBackArr.map((item) => {
						return {
							...item,
							value: item.name,
							label: item.id,
						}
					})
					if (callBackArr.length == 0) {
						cb([{ value: '暂无数据', name: '暂无数据' }])
					} else {
						cb(newarr)
					}
				}, 1000)
			},
			handleSelectTwo() {
				if (this.selectData.length !== 0) {
					this.tableData = this.selectData
					this.dialogGoods = false
				} else {
					this.$confirm('请选择需要添加的商品', '操作失败', {
						showClose: false,
						showCancelButton: false,
						closeOnClickModal: false,
						confirmButtonText: '确定',
						type: 'error',
					})
				}
			},
			handleSelect(item) {
				this.handleshow = false
				this.userData = item
				this.formData.customerId = item.label
				// console.log(this.formData)
			},
			clearUserName() {
				this.handleshow = true
			},
			async handleSave() {
				const res = await getOrderAdd(this.formData)
				if (res.data) {
					this.$message.success('提交成功')
					this.goBack()
				}
			},
			async goBack() {
				const detailPath = await handleActivePath(this.$route, true)
				await this.$router.push('/order/orderlist')
				await this.delVisitedRoute(detailPath)
			},
			goBackReturn() {
				this.$router.push('/order/ordereturn')
			},
			selectGoods(sel, row) {
				this.selectData = sel
			},
			//发货
			async delivery(e, index) {
				let res = await listitemsedit({
					id: e.id,
					status: index,
				})
				if (res.status == '200') {
					this.$message.success('发货成功')
					this.modifyList(index)
				} else {
					this.$message(res.message)
				}
			},
			returnGoods(e) {
				this.dialogFormVisible = true
				this.form = JSON.parse(JSON.stringify(e))
				this.form.customerId = this.customerId
				this.form.status = 1
				sessionStorage.setItem('order', JSON.stringify(e))
			},
			//退货
			async mackOrder() {
				this.form.remarks = this.remarks
				let e = JSON.parse(sessionStorage.getItem('order'))
				// console.log(this.form,'1111111')
				if (this.form.remarks == '') {
					this.$message.warning('请输入退货申请原因')
					return false
				}
				if (this.form.qty > e.qty) {
					this.$message.error('退款数量需小于订单数量')
					return false
				}
				if (this.form.price > e.price) {
					this.$message.error('退款金额需小于订单金额')
					return false
				} 
				let res = await returnGoods({
					id: e.id,
					status: 5,
					orderId: e.orderId
				})
				if (res.status == '200') {
					this.$message.success('退货成功请填写信息生成退货订单')
					this.generate(e)
				} else {
					this.$message(res.message)
				}
			},
			//生成退货订单
			async generate() {
				let time = Date.now();
				this.form.ctime = parseInt(time / 1000)
				let res = await addreturn(this.form)
				if (res.status == '200') {
					this.$message.success('生成退货订单成功')
					this.modifyList(5)
					this.dialogFormVisible = false
				} else {
					this.$message(res.message)
				}
			}
		},
	}
</script>
<style >
	.table_img .cell {
		display: flex !important;
		flex-wrap: wrap !important;
	}
</style>
<style lang="scss" scoped>
	.contents {
		padding: 5px 15px 0;

		.neworder {
			// height: 400px;
			overflow: hidden auto;

			.newOrder-title {
				width: 100%;
				padding: 10px;
				font-size: 16px;
				text-align: left;
				border-bottom: 1px solid #eee;
				margin: 0;

				.newOrder-operation {
					float: right;
					margin-right: 10px;
					vertical-align: middle;
					font-size: 14px;
					color: #03ac54;

					span:not(:last-child) {
						margin-right: 10px;
					}
				}
			}

			.new-order-main {
				position: relative;
				border-bottom: 8px solid #f5f5f5;
				width: 100%;
				padding: 15px 10px;
			}

			.newOrder-address {
				width: 100%;
				padding: 10px;
				text-align: left;
				border-bottom: 8px solid #f5f5f5;
				font-size: 16px;
				line-height: 24px
			}

			.newOrder-address>span {
				margin-right: 15px;
			}

			.newOrder-amount {
				padding: 10px;
				text-align: right;
				font-size: 14px;
				color: #ed3f14;
			}

			.newOrder-remark {
				margin-top: 10px;
				width: 100%;
				height: 50px;
				padding: 0 10px;
				border-bottom: 8px solid #f5f5f5;
			}

			.newOrder-feature {
				text-align: left;
				padding: 15px;
				border-top: 1px solid #eee;
			}
		}
	}
</style>
